package cn.core.tool.interceptors;

import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.lang.reflect.Type;

/**
 * 字符串类型请求参数去首尾空格
 */
@Configuration
@ConditionalOnProperty(prefix = "proconf", name = "gson-serialize-interceptor", havingValue = "true")
public class GsonConfig implements WebMvcConfigurer {

  @Bean
  GsonHttpMessageConverter gsonHttpMessageConverter() {
    GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
    converter.setGson(new GsonBuilder()
        .serializeNulls()
        .registerTypeHierarchyAdapter(String.class, new JsonDeserializer<String>() {
          @Override
          public String deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
            return json.getAsString().trim();
          }
        })
        .create());
    return converter;
  }

}
